﻿using DDD.BackgroundService.Jobs;
using DDD.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Quartz;
using Quartz.AspNetCore;

namespace DDD.BackgroundService
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            await new HostBuilder()
                .ReplaceIConfiguration()
                .AddSerilog(ConfigurationExtension.Configuration.Instance())
                .ConfigureLogging((context, log) =>
                {

                })
                .ConfigureServices((context, serviceCollection) =>
                {
                    serviceCollection.AddQuartz(config =>
                    {
                        config.UseMicrosoftDependencyInjectionJobFactory();

                        var jobKey = new JobKey("RegularWork", "regularWorkGroup");

                        config.AddJob<DownloadImageJob>(jobKey, j => j
                        .WithDescription("My regular work"));

                        config.AddTrigger(t => t
                        .ForJob(jobKey)
                        .StartNow()
                        .WithCronSchedule(DownloadImageJob.CRON)
                        .WithDescription("My regular work trigger"));

                    });

                    serviceCollection.AddQuartzServer(option =>
                    {
                        option.WaitForJobsToComplete = true;
                    });

                    serviceCollection.AddHttpClient(DownloadImageJob.CLIENT_NAME, (serviceProvider, client) =>
                    {
                        var configuration = ConfigurationExtension.Configuration.Instance();
                        string baseUrl = configuration.GetValue<string>(AppSettingsConst.Quartz.DOWNLOAD_URL)!;

                        client.BaseAddress = new Uri(baseUrl);
                    });
                })
                .UseConsoleLifetime()
                .RunConsoleAsync();
        }
    }
}
